<template>
  <div class="app-container">

    <el-row>
      <el-button v-permission="['sys:role:add']" @click="showAddDialog" icon="el-icon-plus" size="small" type="success" round>新增</el-button>
    </el-row>

    <el-table
      :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
      :height="tableHeight"
      row-key="id"
      ref="dataTable"
      v-loading="flagTableLoading"
      stripe
      element-loading-text="加载中"
      highlight-current-row>

      <el-table-column type="index" label="序号" min-width="50"/>
      <el-table-column label="角色名" prop="name" min-width="90"/>
      <el-table-column label="状态" prop="status" min-width="60"
                       :formatter="formatterStatus"
                       :filters="[{text: '启用', value: 1},{text: '禁用', value: 0}]"
                       :filter-method="handleFilterStatusTableData"/>
      <el-table-column label="创建时间" prop="createTime" min-width="180"/>
      <el-table-column label="描述" prop="description" min-width="100"/>
      <el-table-column label="操作" align="center" fixed="right" min-width="200">
        <template slot="header" slot-scope="scope">
          <el-input v-model="search" size="mini" placeholder="输入关键字搜索(只能查询当前页)"/>
        </template>
        <template slot-scope="scope">
          <el-button :disabled="scope.row.name === 'ADMIN'" @click="handleView(scope.$index, scope.row)" type="primary" size="mini">查看</el-button>
          <el-button v-permission="['sys:role:update']"  :disabled="scope.row.name === 'ADMIN'" @click="handleEdit(scope.$index, scope.row)" type="warning" size="mini">编辑</el-button>
          <el-popconfirm title="删除后无法恢复，确定删除吗？" icon="el-icon-info" icon-color="red"
              @confirm="handleDelete(scope.$index, scope.row)">
            <el-button v-permission="['sys:role:del']" :disabled="scope.row.name === 'ADMIN'" slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :page-count="totalPage"
      :total="total"
      layout="->, total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <el-dialog :title="flagDialogAddVisible? '新增' :'角色信息'"
               :visible="flagDialogFormVisible||flagDialogAddVisible"
               @close="closeDialog">
      <el-form :model="form" ref="dialogForm" :rules="formRules">
        <el-form-item label="角色名" prop="name" :label-width="formLabelWidth">
          <el-input v-model="form.name" :disabled="!flagDialogAddVisible" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="描述" prop="description" :label-width="formLabelWidth">
          <el-input v-model="form.description" :disabled="flagFormDisable"/>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="form.status" :disabled="flagFormDisable" placeholder="账号状态">
            <el-option key="r1" label="启用" :value="1"/>
            <el-option key="r0" label="禁用" :value="0"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button v-show="!flagFormDisable || flagDialogAddVisible" type="primary" @click="handleFromConfirm">确 定</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>

  import permission from '@/directive/permission/index' // 权限判断指令

  export default {
  directives: { permission },
  data() {
    return {
      flagDialogFormVisible: false,
      flagDialogAddVisible: false,
      flagFormDisable: false,
      flagTableLoading: false,
      formLabelWidth: '120px',
      tableData: [],
      search: '',
      pageNum: 1,
      pageSize: 10,
      totalPage: 0,
      total: 0,
      // windowWidth: document.documentElement.clientWidth,  //实时屏幕宽度
      tableHeight: document.body.clientHeight-150,   //实时屏幕高度
      form: {
        name: '',
        status: 1,
        description: ''
      },
      formRules:{
        name: [{required:true,type:'string',message: '只允许字母数字和下划线,长度4-10',min:4,max:30,pattern: /^[A-Za-z0-9(:)]+$/,trigger: 'blur'}],
        description: [{ type:'string',message: '20字内',max:20, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.flagTableLoading = true
      this.getRequest("/role/list",{pageNum:this.pageNum,pageSize:this.pageSize}).then(res =>{
        if (res.code === 200) {
          this.tableData = res.content.list
          this.pageNum = res.content.pageNum
          this.pageSize = res.content.pageSize
          this.totalPage = res.content.totalPage
          this.total = res.content.total
        }
        this.flagTableLoading = false;
      }).catch((error) => {
        this.$message({message: error, type: 'error'})
        this.flagTableLoading = false
      })
    },
    formatterStatus(row,column,cellValue,index){
      return cellValue ===1 ? "启用":"禁用"
    },
    handleView(index, row) {
      this.form = row
      this.flagDialogFormVisible = true
      this.flagFormDisable = true
    },
    handleEdit(index, row) {
      this.form = this.cloneDeep(row)
      this.flagDialogFormVisible = true
      this.flagFormDisable = false
    },
    handleDelete(index, row) {
      this.deleteRequest("/role/"+row.id).then(res =>{
        if (res.code === 200) {
          this.$message({message: "删除成功", type: 'success'})
          this.fetchData()
        }else{
          this.$message({message: "删除失败", type: 'error'})
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.fetchData()
    },
    handleFromConfirm(){
      this.$refs["dialogForm"].validate(valid => {
        if (valid) {
          if (this.flagDialogAddVisible) {
            this.postRequest("/role",this.form).then(res => {
              if (res.code === 200) {
                this.$message({message: "添加成功", type: 'success'})
                this.flagDialogAddVisible = false
                this.fetchData()
              }else{
                this.$message({message: "添加失败", type: 'error'})
              }
            });
          }else{
            if (!this.flagFormDisable) {
              this.putRequest("/role",this.form).then(res => {
                if (res.code === 200) {
                  this.$message({message: "更新成功", type: 'success'})
                  this.flagDialogFormVisible = false
                  this.fetchData()
                }else{
                  this.$message({message: "更新失败", type: 'error'})
                }
              })
            }
          }
        }
      })
    },
    closeDialog(){
      this.flagDialogAddVisible = false
      this.flagDialogFormVisible = false
    },
    showAddDialog(){
      this.form = {
        name: '',
        status: 1,
        description: ''
      }
      this.flagFormDisable = false
      this.flagDialogAddVisible = true
    },
    handleFilterStatusTableData(value, row, column){
      let property = column['property'];
      return row[property] === value
    }
  }
}
</script>
